//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    showLoading: true,
    noMoretip: false,
    page: 0,
    searchVal:'',
  
  },
  onLoad: function (e) {
    console.log(e.mid);
    var that = this;
    var id = '', type = '', cvalue = '', climit = '', mid = (e.mid && e) ? e.mid : '';
    if (e && e.id) {
      id = e.id;
    }
    if (e && e.type) {
      type = e.type;
    }
    if (e && e.value) {
      cvalue = e.value;
    }
    if (e && e.limit) {
      climit = e.limit;
    }
    if (e && e.title) {
      that.setData({
        title: e.title
      })
      app.setNavtitle(e.title);
    } else {
      app.setNavtitle('商品搜索');
    }
    that.setData({
      cid: id,
      ctype: type,
      cvalue: cvalue,
      climit: climit,
      mid: mid
    })
    this.getList();
  },
  onShow: function () {
  },
  getList(){
    let that = this;
    var data = {};
    var page = that.data.page;
    var searchVal = that.data.searchVal;
    data.map = 'applet_goods_list';
    data.page = page;
    data.cid = that.data.cid;
    data.ctype = that.data.ctype;
    
    // todo wanyiming
    if (app.globalData.checkData.check) {
      data.kind2 = '221754'; // 腾讯审核ID
    }

    data.mid= that.data.mid;
    if (searchVal){
      data.keyword = searchVal;
      console.log("搜索关键字");
      console.log(searchVal);
    }
    //发起请求，获取列表列表
    // wx.showToast({
    //   title: '加载中',
    //   icon: 'loading',
    //   mask: true,
    //   duration: 10000
    // });
    
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          var allArr = [];
          var initArr = that.data.shopGoods ? that.data.shopGoods:'[]';
          var curArr = res.data.data;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data;
          }
          that.setData({
            shopGoods: allArr,
            
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false,
              
            });
          }
          console.log(that.data.shopGoods);
        } else {
          console.log(res.data)
          if (page <= 0) {
            that.setData({
              shopGoods: []
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false,
              
            });
          }
        }
      },
      complete: function () {
        wx.hideToast();
        wx.stopPullDownRefresh();
      }
    });
  },
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    this.getList();
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      
      page++;
      that.setData({
        
        page: page,
     
      });
      that.getList();
    }
  },
  goodDetail: function (e) {
    var goodId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/subpages1/goodDetail/goodDetail?id=' + goodId
    })
  },
  cancel:function(){
    wx.navigateBack({
      delta: 1
    })
  },
  searchValChange:function(e){
    var searchVal = e.detail.value;
    this.setData({
      searchVal: searchVal
    });
  },
  searchGood:function(){
    var that = this;
    var searchVal = that.data.searchVal;
    if (searchVal.length>0){
      console.log(searchVal);
      that.onPullDownRefresh();
    }else{
      app.errorTip(that, '请输入搜索商品关键字', 2000);
    }
    
  },
  addminusCart: function (e) {
    var that = this;
    var curgood = e.currentTarget.dataset.curgood;
    var smallNum = curgood.smallNum;
    that.setData({
      curgood: curgood,
      buyNumber: smallNum,
      curImgformat: '',
      chooseGuige: {
        stock: curgood.stock
      },
      isShowFormat: true
    })
  },
  hideFormat: function () {
    var that = this;
    that.setData({
      isShowFormat: false
    })
  },
  stoptouchmove: function (e) {
    console.log(e);
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.target.dataset.findex;
    var index = e.target.dataset.index;
    var curgood = that.data.curgood;
    if (findex == 0) {
      var curImgformat = curgood.formatList[0].value[index];
      that.setData({
        curImgformat: curImgformat
      })
    }
    var checkFormat = [];
    for (var i = 0; i < curgood.formatList[findex].value.length; i++) {
      curgood.formatList[findex].value[i].checked = false;
    }
    curgood.formatList[findex].value[index].checked = true;
    for (var i = 0; i < curgood.formatList.length; i++) {
      for (var j = 0; j < curgood.formatList[i].value.length; j++) {
        if (curgood.formatList[i].value[j].checked) {
          checkFormat.push(curgood.formatList[i].value[j]);
        }
      }
    }
    that.setData({
      curgood: curgood,
      checkFormat: checkFormat
    })
    if (checkFormat.length == curgood.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
      }
      console.log(formatName);
      var chooseGuige = curgood.formatValue[formatName];
      chooseGuige.formatName = formatName;
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    }
  },
  changeNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var buyNum = parseInt(that.data.buyNumber);
    var stock = parseInt(that.data.chooseGuige.stock);
    var purchase = parseInt(that.data.curgood.purchase);
    var disabled = e.currentTarget.dataset.disable;
    if (disabled) return;
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
      }
      if (buyNum < stock) {
        if (buyNum < purchase) {
          buyNum++;
        } else {
          app.errorTip(that, '超出限购数量', 2000);
        }
      } else {
        buyNum = stock;
      }
    } else {
      var smallNum = that.data.curgood.smallNum > 1 ? that.data.curgood.smallNum : 1;
      if (buyNum > smallNum) {
        buyNum--;
      } else {
        buyNum = smallNum;
      }
    }

    that.setData({
      buyNumber: buyNum
    })
  },
  numChange: function (e) {
    var that = this;
    var stock = that.data.chooseGuige.stock;
    var val = e.detail.value;
    val = val.replace(/\D/g, '');
    if ((parseInt(val)) > parseInt(stock)) {
      that.setData({
        buyNumber: stock
      })
    } else {
      that.setData({
        buyNumber: val
      })
    }
  },
  confirmAddcart: function (e) {
    var that = this;
    var curgoodCart = that.data.curgoodCart;
    var gid = e.currentTarget.dataset.gid;
    var gfid = that.data.chooseGuige.id;
    var num = parseInt(that.data.buyNumber);
    var isFormat = that.data.curgood.hasFormat;
    var stock = parseInt(that.data.chooseGuige.stock);
    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: num,
      add: 1
    }
    if (isFormat && !gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!data.num || data.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + data.num);
    if (data.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.setData({
            isShowFormat: false,
            cartNum: res.data.data.cartNum
          })
          that.hideFormat();
          app.errorTip(that, '已成功加入购物车', 2000);
          app.globalData.requestCartNum = res.data.data.cartNum;
          app.setCartnum();//更新购物车数量
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
      }
    });
  },
})